package com.foton.designmodel.proxy;


import com.foton.designmodel.share.session.Session;
import com.foton.designmodel.share.session.UserThreadLocal;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


/**
 * 【代理模式，根据文件格式，上传上传不同的平台进行案例编写】
 *
 */
@Slf4j
@Component
@ConfigurationProperties(prefix = "upload")
//@ConditionalOnProperty(prefix = "jod.schedule",name = "task") 配置文件中包含此注解才能进行装此配置类到容器
public class SystemFileProxy implements ApplicationContextAware {


    @Setter
    private Map<String, List<String>> fileMap;

    private ApplicationContext act;

    @Resource
    private UserThreadLocal userThreadLocal;

    public String uploadFile(MultipartFile file) {

        try {
            // 文件大小
            byte[] fileBytes = file.getBytes();
            //文件原始名称
            String filename = file.getOriginalFilename();

            //获取文件的后缀  例如：png,jpg,mp4等后缀
            String fileExtensionName = StringUtils.getFilenameExtension(filename);
            Session session = userThreadLocal.get();
            log.info("当前用户信息为=====> {}",session.getUserName());


            //根据后缀，匹配对应的所需要的文件管理模式
            // aliyunOssFileManage：mp4，avi; fastdfsFileManage: jpg,png

            for (Map.Entry<String, List<String>> entry : fileMap.entrySet()) {
                List<String> suffixList = entry.getValue();

                for (String suffixValue : suffixList) {
                    if (suffixValue.equals(fileExtensionName)) {
                        return act.getBean(entry.getKey(), SystemFileManageApi.class).upload(fileBytes, filename);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        return "null";
    }


    @Override
    public void setApplicationContext(ApplicationContext act) throws BeansException {
//        act.getBeansWithAnnotation() 判断Bean是否有指定的注解

        this.act = act;
    }


}
